//
//  TLCategoryManger.m
//  FunnyVideo
//
//  Created by 李鑫 on 16/1/3.
//  Copyright © 2016年 NewEggTech. All rights reserved.
//

#import <AVOSCloud/AVOSCloud.h>
#import "TLCategoryManger.h"

@interface TLCategoryManger ()
@property (nonatomic,copy) NSDictionary *imageCached;

@end
@implementation TLCategoryManger
+ (TLCategoryManger *)manger{
    static dispatch_once_t onceToken;
    static TLCategoryManger *manger;
    dispatch_once(&onceToken, ^{
        manger = [[TLCategoryManger alloc] init];
    });
    
    return manger;
}

- (id)init{
    self = [super init];
    
    if(self)
    {
        self.imageCached = [[NSDictionary alloc] init];
    }
    
    return self;
}
+ (void)cacheImages{
    NSMutableDictionary *dics = [[NSMutableDictionary alloc] init];
    
    AVQuery *categoryQueries = [AVQuery queryWithClassName:@"Category"];
    
    [categoryQueries findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            for(AVObject *cate in objects)
            {
                AVFile *thumb = [cate objectForKey:@"thumb"];
                UIImage *imageData =  [UIImage imageWithData:[thumb getData]];
                [dics setObject:imageData forKey:[cate objectForKey:@"category"]];
            }
            NSLog(@"category 缓存完毕");
        });
    }];
}


+ (void)imageForCategory:(NSString *)category completion:(void(^)(UIImage *cachedImage))completion{
    UIImage *image = [UIImage imageNamed:@"error-black"];
    if([[[TLCategoryManger manger] imageCached] objectForKey:category])
    {
        image =[[[TLCategoryManger manger] imageCached] objectForKey:category];
    completion(image);
    }
    else
    {
        AVQuery *categoryQueries = [AVQuery queryWithClassName:@"Category"];
        if(category)
        [categoryQueries whereKey:@"category" equalTo:category];
        
        [categoryQueries findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            AVObject *obj = [objects lastObject];
            
                AVFile *file = [obj objectForKey:@"thumb"];
                
                UIImage *image = [UIImage imageWithData:[file getData]];
            
            completion(image);
        }];
        
        [TLCategoryManger cacheImages];
    }
    

}
@end
